package com.example.app_down_test;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.histone.lib_download.DownloadFactory;
import com.histone.lib_download.downloader.DownloadService;
import com.histone.lib_download.downloader.FileInfo;
import com.histone.lib_download.localbroadcast.LocalBroadcastHolder;

public class MainActivity extends AppCompatActivity {


    private final String[] permission = {Manifest.permission.READ_EXTERNAL_STORAGE
            , Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.RECORD_AUDIO
    };

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActivityCompat.requestPermissions(this, permission, 11);
        initDownloader();

        DownloadFactory.checkDownload(this);
        findViewById(R.id.tv).setOnClickListener(v -> {
            String url = "https://dd.myapp.com/sjy.00007/sjy.00002/16891/apk/65F355BCED77567B3821D63522113CA9.apk?fsname=com.kiloo.subwaysurf_40210.apk";
//            FileInfo info = new FileInfo(url, DownloadFactory.getDefaultFile());
            FileInfo info = new FileInfo(url, getExternalCacheDir().getPath());

            Intent intent = new Intent(this, DownloadService.class);
            intent.setAction(DownloadService.DOWNLOAD_START);
            intent.putExtra(DownloadService.KEY_FILE_INFO, info);
            intent.putExtra(DownloadService.KEY_CHECK_SPACE, true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent);
            } else {
                startService(intent);
            }
        });
    }

    LocalBroadcastManager localBroadcastManager;
    IntentFilter intentFilter;
    LocalReceiver localReceiver;

    private void initDownloader() {
        Log.e("SD-count", DownloadFactory.getFreeSpace(this));
        Log.e("SD-count", DownloadFactory.getFreeSpaceLength(this) + "");
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadcastHolder.LOCAL_BROADCAST_ACTION);
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(localReceiver);
        super.onDestroy();
    }
}